package com.gzxw.mogublog.web.config;

import com.gzxw.mogublog.utils.JsonUtils;
import com.gzxw.mogublog.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @program: mogublog
 * @author: gzxw
 * @create: 2023-04-08 16:12
 **/
@Component
@Slf4j
public class AuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        // 得到请求头中的token
        String accessToken = httpServletRequest.getHeader("Authorization");

        if (StringUtils.isNotEmpty(accessToken)) {
            //从redis中获取
            String userInfo = stringRedisTemplate.opsForValue().get("USER_TOKEN" + ":" + accessToken);
            if (StringUtils.isNotEmpty(userInfo)) {
                Map<String, Object> map = JsonUtils.jsonToMap(userInfo);
                // 将userUid存入到request中
                httpServletRequest.setAttribute("token",accessToken);
                httpServletRequest.setAttribute("user_uid",map.get("uid"));
                httpServletRequest.setAttribute("user_name",map.get("nickName"));
                log.info("解析出来的用户:{}",map.get("nickName"));
            }
        }
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }
}
